package com.aos.iot.socket.common.annotation;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;

public class CmdEventAnnotationScanner implements BeanPostProcessor {

    private final List<Class<? extends Annotation>> annotations =
            Arrays.asList(OnConnect.class, OnDisconnect.class, OnCmdEvent.class);

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        ReflectionUtils.doWithMethods(bean.getClass(),
                method -> TcpEventListenerHub.addListener(bean, method),
                method -> {
                    for (Class<? extends Annotation> annotationClass : annotations) {
                        if (method.isAnnotationPresent(annotationClass)) {
                            return true;
                        }
                    }
                    return false;
                });
        return bean;
    }

}
